package com.avic.service.impl;

import com.avic.common.util.AssertUtil;
import com.avic.common.util.ex.BizErrorCode;
import com.avic.common.util.ex.BizException;
import com.avic.dal.condition.PageQueryFileListCondition;
import com.avic.dal.model.FileConfigManager;
import com.avic.dal.model.FileManager;
import com.avic.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.List;

/**
 * @Author huangsheng on 2019/1/7
 */
@Service
@Slf4j
public class FileServiceImpl extends AbstractServiceImpl implements FileService {

    @Override
    public List<FileManager> itemList(PageQueryFileListCondition pageQueryFileListCondition) {
        return fileManageMapper.itemList(pageQueryFileListCondition);
    }

    @Override
    public int queryRecordsTotal(PageQueryFileListCondition pageQueryFileListCondition) {
        return fileManageMapper.queryRecordsTotal(pageQueryFileListCondition);
    }

    @Override
    public int createFileRecord(FileManager fileManager) {
        try {
            fileManageMapper.insert(fileManager);
            return fileManager.getId();
        } catch (Exception e) {
            log.error("新增文件上传记录发生错误 {}", e.getMessage());
            throw new BizException(BizErrorCode.SYSTEM_ERROR, "新增附件记录发生错误");
        }
    }


    @Override
    @Transactional(rollbackFor = BizException.class)
    public void delete(int fileId) {

        FileManager fileManager = fileManageMapper.queryItemById(fileId);
        AssertUtil.isTrue(null != fileManager, BizErrorCode.PARAM_ERROR, "资源已经被删除");

        try {
            fileManageMapper.delete(fileId);

            String fileUrl = fileManager.getFileUrl();
            log.info("文件路径 {}", fileUrl);
            File file = new File(commonProperties.getUploadLocation() + fileUrl);
            if (file.exists() && file.isFile()) {
                log.info("存在文件 {}. 删除文件", commonProperties.getUploadLocation() + fileUrl);
                file.delete();
            }
        } catch (Exception e) {
            log.error("删除文件上传记录发生错误 {}", e.getMessage());
            throw new BizException(BizErrorCode.SYSTEM_ERROR, "删除附件记录发生错误");
        }

    }

    @Override
    public int updateFileCountConfig(int fileCountConfig) {
        return fileManageMapper.updateFileCountConfig(fileCountConfig);
    }

    @Override
    public FileConfigManager selectFileCountConfig() {
        return fileManageMapper.selectFileCountConfig();
    }

    @Override
    public int fileTotalCount() {
        return fileManageMapper.fileTotalCount();
    }

    @Override
    public FileManager getItemById(int fileId) {
        return fileManageMapper.queryItemById(fileId);
    }
}
